package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"new/models"
	"strconv"
	"time"
)

type NewController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	status := c.GetString("status")
	news := models.New{
		Title:  title,
		Time:   time,
		Status: status,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: news,
		}
		c.ServeJSON()
	}
}

func (c *NewController) List() {
	pageData := make(map[string]interface{})
	query := models.DB.Model(&models.New{})

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)

	key := "people-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()

	if err != nil {
		var count int64
		query.Count(&count)
		offset := (page - 1) * size
		var news []models.New
		err = query.Offset(offset).Limit(size).Find(&news).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["news"] = news
			pageData["count"] = count
			jsonByte, _ := json.Marshal(pageData)
			value := string(jsonByte)
			models.Rdb.Set(key, value, time.Second*5)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "展示成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *NewController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	status := c.GetString("status")
	news := models.New{
		Title:  title,
		Time:   time,
		Status: status,
	}
	err := models.DB.Where("ID=?", id).Save(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: news,
		}
		c.ServeJSON()
	}
}

func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("ID=?", id).Delete(&models.New{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
